package com.yljk.yljkproject.utils

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.format.Time
import android.view.*
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import androidx.core.view.ViewCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alsk.rn.common.model.SchemeModule.RNSchemeBuilder
import com.alsk.rn.common.util.RNPageUtil
import com.alsk.rn.common.util.ReactUtils
import com.facebook.react.bridge.ReactContext
import com.yilijk.base.utils.CommonUtils
import com.yljk.yljkproject.R
import com.yljk.yljkproject.adapter.PhoneAdapter
import org.json.JSONException
import org.json.JSONObject
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
import java.util.*
import javax.net.ssl.*
import javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier
import javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory

object ReactUtils {



    //打电话变量
    var phoneList: RecyclerView? = null;
    var cancelDialog: TextView? = null;
    var phoneAdapter: PhoneAdapter? = null;

    private val handler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
        }
    }

    /**
     * nativemap 解析
     */
    fun getPramasJSONObject(string: String) :JSONObject?{
        var dataStr : String? = null
        var jsonObject:JSONObject? =null
        try {
            jsonObject = JSONObject(string)
//            dataStr = jsonObject.getString("NativeMap")
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        return jsonObject
    }

    fun delNativeMap(string: String) :String?{
        var dataStr : String? = null
        var jsonObject:JSONObject? =null
        try {
            jsonObject = JSONObject(string)
            dataStr = jsonObject.getString("NativeMap")
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        return dataStr
    }

    const val EXTENSION = ".mp3"
    fun getVoiceFileName(uid: String): String? {
        val now = Time()
        now.setToNow()
        return uid + now.toString().substring(0, 15) + EXTENSION
    }

    //android to rn  页面跳转
     fun push(context: Context, pluginId: String, compontName: String) {
        if(compontName == null){
            return
        }
        val schemeModule = RNSchemeBuilder()
                .pluginId(pluginId)
                .moduleId("index")
                .componentName(compontName)
                .build()
        ReactUtils.openRnPageView(context, schemeModule)
    }
    fun push(context: Context, pluginId: String, compontName: String,bundle:Bundle) {
        if(compontName == null){
            return
        }
        val schemeModule = RNSchemeBuilder()
                .pluginId(pluginId)
                .moduleId("index")
                .componentName(compontName)
                .launchmode("singTop")
                .params(bundle)
                .build()
        ReactUtils.openRnPageView(context, schemeModule)
    }

    //        SchemeModule build = new SchemeModule.RNSchemeBuilder()
//                .pluginId(pluginId)
//                .moduleId("index")
//                .componentName(componentName)
//                .params(bundle)
//                .build();
//        com.alsk.rn.common.util.ReactUtils.openRnPageView(context, build);
//    fun pushSingTask(context: Context, pluginId: String, compontName: String,bundle:Bundle){
//        val intent = Intent(context, RNSingTaskActivity::class.java)
//        intent.putExtra("intent_key_params", bundle)
//        intent.putExtra("intent_key_plugin_id", pluginId)
//        intent.putExtra("intent_key_module_id", "index")
//        intent.putExtra("intent_key_component_name", compontName)
//        bundle.putString("pageTag", RNPageUtil.createPageTag(pluginId, compontName))
//        context.startActivity(intent)
//    }


    fun openPhoneView(reactContext: ReactContext,tels:ArrayList<String>){
        val popupWindow = PopupWindow()
        popupWindow.height = LinearLayout.LayoutParams.WRAP_CONTENT
        popupWindow.width = LinearLayout.LayoutParams.MATCH_PARENT
        val view: View = LayoutInflater.from(reactContext).inflate(R.layout.phone_dialog_layout, null)
        phoneList = view.findViewById<View>(R.id.phone_list) as RecyclerView?
        cancelDialog = view.findViewById<View>(R.id.cancel_dialog) as TextView?
        phoneList!!.layoutManager = LinearLayoutManager(reactContext)
        phoneAdapter = PhoneAdapter(R.layout.item_phone, tels)
        phoneList!!.adapter = phoneAdapter
        phoneAdapter!!.notifyDataSetChanged()
        popupWindow.contentView = view
        popupWindow.animationStyle = R.style.popwindow_anim_style
        popupWindow.isOutsideTouchable = true
        popupWindow.isFocusable = true
        popupWindow.showAtLocation(reactContext.currentActivity!!.window.decorView, Gravity.BOTTOM, 0, 0)
        backgroundAlpha(reactContext, 0.5f)
        popupWindow.setOnDismissListener { backgroundAlpha(reactContext, 1.0f) }
        cancelDialog?.setOnClickListener(View.OnClickListener { popupWindow.dismiss() })
        phoneAdapter!!.setOnItemClickListener { adapter, view, position -> callphone(reactContext, tels.get(position)) }
    }

    // 设置屏幕透明度
    fun backgroundAlpha(reactContext: ReactContext,bgAlpha: Float) {
        handler.post(Runnable {
            val lp: WindowManager.LayoutParams = reactContext.currentActivity!!.window.attributes;
            lp.alpha = bgAlpha // 0.0~1.0
            reactContext.currentActivity!!.window.attributes=lp
        })
    }

    //拨打电话
    fun callphone(reactContext: ReactContext,tel: String){
        val packageManager: PackageManager = reactContext.getPackageManager()
        val i = packageManager.checkPermission("android.permission.CALL_PHONE", reactContext.getPackageName())
        if (!CommonUtils.checkPermission(reactContext, Manifest.permission.CALL_PHONE)) {
            CommonUtils.getModuleCommonUtils().setRequestPermission(reactContext.currentActivity, arrayOf(
                    Manifest.permission.CALL_PHONE), 10001)
        } else {
            val intent = Intent("android.intent.action.CALL", Uri.parse("tel:$tel"))
            //开启系统拨号器
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            reactContext.startActivity(intent)
        }
    }

    //    设置状态栏颜色
    fun setStatusBarColor(activity: Activity, statusColor: Int) {
        val window = activity.window
        //取消状态栏透明
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        //添加Flag把状态栏设为可绘制模式
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        //设置状态栏颜色
        window.statusBarColor = statusColor
        //设置系统状态栏处于可见状态
        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE
        //让view不根据系统窗口来调整自己的布局
        val mContentView = window.findViewById<View>(Window.ID_ANDROID_CONTENT) as ViewGroup
        val mChildView = mContentView.getChildAt(0)
        if (mChildView != null) {
            ViewCompat.setFitsSystemWindows(mChildView, false)
            ViewCompat.requestApplyInsets(mChildView)
        }
    }

//        //修改文字颜色
//    private fun setAndroidNativeLightStatusBar(activity: Activity, color: Int) {
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//                //判断是否为小米或魅族手机，如果是则将状态栏文字改为黑色
////                if (MIUISetStatusBarLightMode(activity, true) || FlymeSetStatusBarLightMode(activity, true)) {}
//                    //设置状态栏为指定颜色
//                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //5.0
//                        activity.window.statusBarColor = color
//                    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { //4.4
//                        //调用修改状态栏颜色的方法
//                        setStatusBarColor(activity, color)
//                    }
//                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                    //如果是6.0以上将状态栏文字改为黑色，并设置状态栏颜色
//                    activity.window.setBackgroundDrawableResource(android.R.color.transparent)
//                    activity.window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
//                    activity.window.statusBarColor = color
//
//                    //fitsSystemWindow 为 false, 不预留系统栏位置.
//                    val mContentView = activity.window.findViewById(Window.ID_ANDROID_CONTENT) as ViewGroup
//                    val mChildView = mContentView.getChildAt(0)
//                    if (mChildView != null) {
//                        ViewCompat.setFitsSystemWindows(mChildView, true)
//                        ViewCompat.requestApplyInsets(mChildView)
//                    }
//                }
//            }


     fun setAndroidNativeLightStatusBar(activity: Activity, dark: Boolean) {
        val decor = activity.window.decorView
        if (dark) {
            decor.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        } else {
            decor.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
        }
    }


    /**
     * 绕过验证
     * @return
     */
    fun createIgnoreVerifySSL(sslVersion: String): SSLSocketFactory {
        var sc = SSLContext.getInstance(sslVersion);
        val trustAllCerts: Array<TrustManager> = arrayOf(object : X509TrustManager {
            @Throws(CertificateException::class)
            override fun checkClientTrusted(
                    chain: Array<java.security.cert.X509Certificate>, authType: String) {
            }

            @Throws(CertificateException::class)
            override fun checkServerTrusted(chain: Array<java.security.cert.X509Certificate>, authType: String) {
            }

            override fun getAcceptedIssuers(): Array<X509Certificate?> {
                return arrayOfNulls(0)
            }
        })

        sc!!.init(null, trustAllCerts, java.security.SecureRandom())

        // Create all-trusting host name verifier
        val allHostsValid = HostnameVerifier { _, _ -> true }
        /***
         * 如果 hostname in certificate didn't match的话就给一个默认的主机验证
         */
        setDefaultSSLSocketFactory(sc.getSocketFactory());
        setDefaultHostnameVerifier(allHostsValid);
        return sc.socketFactory;
    }
}

